package com.seeyon.apps.brwh.service;

import com.seeyon.apps.brwh.kit.BookMarksUtil;
import com.seeyon.apps.brwh.kit.StrKit;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.filemanager.Constants;
import com.seeyon.ctp.common.filemanager.manager.FileManager;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.common.po.filemanager.Attachment;
import com.seeyon.ctp.common.po.filemanager.V3XFile;
import com.seeyon.ctp.organization.bo.*;
import com.seeyon.ctp.organization.manager.OrgManager;
import com.seeyon.ctp.services.FileDownloadExporter;
import com.seeyon.ctp.services.ServiceException;
import com.seeyon.ctp.util.UUIDLong;
import org.apache.commons.logging.Log;
import org.apache.poi.xwpf.usermodel.Document;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 表单转文档逻辑处理类
 */
public class FormTableWordService {
    private static final Log log = CtpLogFactory.getLog(FormTableWordService.class);
    private EnumManager enumManagerNew = (EnumManager) AppContext.getBean("enumManagerNew");
    private OrgManager orgManager = (OrgManager)AppContext.getBean("orgManager");

    private FileManager fileManager = (FileManager)AppContext.getBean("fileManager");
    /**
     * 处理表单转word
     * @param dataMap
     * @return
     */
    public Map<String,Object> formTableWord(Map<String,Object> dataMap) throws IOException {
        HashMap<String, Object> resultMap = new HashMap<>();
        //获取到的模板名称
        String mbName = dataMap.get("mbName").toString();
        //获取主表数据
        List<Map<String,Object>> masterDataList = (List<Map<String, Object>>) dataMap.get("masterData");
        //获取明细表数据
        List<Map<String,Object>> subTableDataList = (List<Map<String,Object>>) dataMap.get("subDataList");
        //获取上传的模板信息
        List<Map<String, Object>> mbMapDataList = masterDataList.stream().filter(m -> m.get("display").toString().equals(mbName)).collect(Collectors.toList());
        if(mbMapDataList.isEmpty()){
            resultMap.put("status","0");
            resultMap.put("data",null);
            resultMap.put("msg","表单不存在【表单转word模板】控件！！");
            return resultMap;
        }
        FileOutputStream out = null;
        FileInputStream fileInputStream = null;
        File newFile = null;
        File toFile = null;
        try {
            //获取上传模板的文件
            String mbFielId = StrKit.str(getFieldTypeValue(mbMapDataList.get(0)).get("data")).split(",")[0];
            V3XFile v3XFile = fileManager.getV3XFile(Long.parseLong(mbFielId));
            if(v3XFile == null){
                resultMap.put("status","0");
                resultMap.put("data",null);
                resultMap.put("msg","没找到对应的范本，保存待发后再试！");
                return resultMap;
            }
            String filename = v3XFile.getFilename();
            String value = filename.split("\\.")[1];
            if(!value.equals("docx")){
                resultMap.put("status","0");
                resultMap.put("data",null);
                resultMap.put("msg","范本格式错误，仅支持【docx】的格式");
                return resultMap;
            }
            //获取下载临时文件目录
            String filePath = AppContext.getCfgHome().getCanonicalPath();
            filePath = filePath.replace("WEB-INF" + File.separator + "cfgHome", "fileTemp" + File.separator);
            String basePath = filePath + File.separator;
            newFile = new File(basePath + mbFielId+"_"+v3XFile.getFilename());

            out = new FileOutputStream(newFile.getPath());
            FileDownloadExporter downloadExporter = new FileDownloadExporter();
            downloadExporter.processDownload(v3XFile.getId()+"", out);

            //重新创建一个文件
            toFile = new File(basePath + "new_"+v3XFile.getFilename());

            //转换主表数据
            HashMap<String, Map<String,Object>> main = new HashMap<>();
            for (Map<String, Object> stringObjectMap : masterDataList) {
                Map<String, Object> fieldTypeValue = getFieldTypeValue(stringObjectMap);
                if(StrKit.str(fieldTypeValue.get("type")).equals("String")){
                    if(!StrKit.str(fieldTypeValue.get("data")).equals("")){
                        main.put(StrKit.str(stringObjectMap.get("display")),fieldTypeValue);
                    }else{
                        if(fieldTypeValue.get("data") != null){
                            main.put(StrKit.str(stringObjectMap.get("display")),fieldTypeValue);
                        }
                    }
                }else{
                    fieldTypeValue.put("data","");
                    fieldTypeValue.put("type","String");
                    main.put(StrKit.str(stringObjectMap.get("display")),fieldTypeValue);
                }

            }
            //转换明细表数据
            Map<String, List<Map<String, Map<String,Object>>>> subTableDatas = new LinkedHashMap<String, List<Map<String, Map<String,Object>>>>();
            for (Map<String, Object> subTableMap : subTableDataList) {
                List<List<Map<String,Object>>> subDataList = (List<List<Map<String,Object>>>)subTableMap.get("dataList");
                //循环每一行
                List<Map<String, Map<String,Object>>> sonlist = new ArrayList<Map<String,  Map<String,Object>>>();

                for (List<Map<String,Object>> subDataMap : subDataList) {
                    HashMap<String, Map<String,Object>> subData = new HashMap<>();
                    //循环每一个字段
                    for (Map<String, Object> stringObjectMap : subDataMap) {
                        Map<String, Object> fieldTypeValue = getFieldTypeValue(stringObjectMap);
                        if(StrKit.str(fieldTypeValue.get("type")).equals("String")){
                            if(!StrKit.str(fieldTypeValue.get("data")).equals("")){
                                subData.put(StrKit.str(stringObjectMap.get("display")),fieldTypeValue);
                            }
                        }else{
                            if(fieldTypeValue.get("data") != null){
                                subData.put(StrKit.str(stringObjectMap.get("display")),fieldTypeValue);
                            }
                        }

                    }
                    sonlist.add(subData);
                }
                subTableDatas.put(StrKit.str(subTableMap.get("tableDisplay")),sonlist);
            }

            //开始进行套红处理
            BookMarksUtil.addBookMarks(newFile, toFile, main, subTableDatas);

            //上传套红的附件回写表单
            fileInputStream = new FileInputStream(toFile);

            //上传文件
            List<Attachment> atts = new ArrayList();
            ApplicationCategoryEnum category = ApplicationCategoryEnum.global;
            Constants.ATTACHMENT_TYPE type = Constants.ATTACHMENT_TYPE.FILE;
            V3XFile upV3XFile = fileManager.save(fileInputStream, category, toFile.getName(), new Date(), false);
            fileManager.save(upV3XFile);
            Attachment att = new Attachment(upV3XFile, category, type);
            att.setSubReference(UUIDLong.longUUID());
            atts.add(att);

            resultMap.put("status","1");
            resultMap.put("data",atts);
            resultMap.put("msg","转换成功");
        }catch (Exception e){
            log.info("word套红异常：",e);
            resultMap.put("status","0");
            resultMap.put("data",null);
            resultMap.put("msg","word套红异常");
        }finally {
            if(out != null){
                out.close();
            }
            if(fileInputStream != null){
                fileInputStream.close();
            }
            if(toFile != null){
                toFile.delete();
            }
            if(newFile != null){
                newFile.delete();
            }
        }
        return resultMap;
    }


    /**
     * 根据不同的表单控件类型取值
     * @param mapData
     * @return
     */
    private Map<String,Object> getFieldTypeValue(Map<String,Object> mapData) throws BusinessException {
        HashMap<String, Object> valueMap = new HashMap<>();
        String fieldType = StrKit.str(mapData.get("fieldType"));
        if(fieldType.equals("datetime") || fieldType.equals("text")||fieldType.equals("linenumber") || fieldType.equals("textarea") || fieldType.equals("date")){
            valueMap.put("type","String");
            valueMap.put("data",StrKit.str(mapData.get("value")));
        }else if(fieldType.equals("checkbox")){
            valueMap.put("type","String");
            valueMap.put("data",StrKit.str(mapData.get("value")).equals("1") ? "是" : "否");
        }else if(fieldType.equals("select")){
            String value = "";
            value = StrKit.str(mapData.get("value"));
            if(!value.equals("")){
                //枚举转换
                CtpEnumItem ctpEnumItem = enumManagerNew.getCtpEnumItem(Long.parseLong(value));
                value = ctpEnumItem.getShowvalue();
            }
            valueMap.put("type","String");
            valueMap.put("data",value);
        }else if(fieldType.equals("attachment")){
            valueMap.put("type","String");
            valueMap.put("data",StrKit.str(mapData.get("value")));
        }else if(fieldType.equals("member")){
            String value = "";
            value = StrKit.str(mapData.get("value"));
            if(!"".equals(value)){
                V3xOrgMember memberById = orgManager.getMemberById(Long.parseLong(value));
                value = memberById.getName();
            }
            valueMap.put("type","String");
            valueMap.put("data",value);
        }else if(fieldType.equals("post")){
            String value = "";
            value = StrKit.str(mapData.get("value"));
            if(!"".equals(value)){
                V3xOrgPost postById = orgManager.getPostById(Long.parseLong(value));
                value = postById.getName();
            }
            valueMap.put("type","String");
            valueMap.put("data",value);
        }else if(fieldType.equals("department")){
            String value = "";
            value = StrKit.str(mapData.get("value"));
            if(!"".equals(value)){
                V3xOrgDepartment departmentById = orgManager.getDepartmentById(Long.parseLong(value));
                value = departmentById.getName();
            }
            valueMap.put("type","String");
            valueMap.put("data",value);
        }else if(fieldType.equals("account")){
            String value = "";
            value = StrKit.str(mapData.get("value"));
            if(!"".equals(value)){
                V3xOrgUnit unitById = orgManager.getUnitById(Long.parseLong(value));
                value = unitById.getName();
            }
            valueMap.put("type","String");
            valueMap.put("data",value);
        }else if(fieldType.equals("level")){
            String value = "";
            value = StrKit.str(mapData.get("value"));
            if(!"".equals(value)){
                V3xOrgLevel levelById = orgManager.getLevelById(Long.parseLong(value));
                value = levelById.getName();
            }
            valueMap.put("type","String");
            valueMap.put("data",value);
        }else if(fieldType.equals("image")){
            String value = "";
            value = StrKit.str(mapData.get("value"));
            //获取图像文件流
            if(!"".equals(value)){
                value = value.split(",")[0];
                V3XFile v3XFile = fileManager.getV3XFile(Long.valueOf(value));
                if(v3XFile.getMimeType().equals("image/jpeg")){
                    valueMap.put("imgType",Document.PICTURE_TYPE_JPEG);
                }else if(v3XFile.getMimeType().equals("image/png")){
                    valueMap.put("imgType",Document.PICTURE_TYPE_PNG);
                }
                InputStream fileInputStream = fileManager.getFileInputStream(Long.valueOf(value));
                valueMap.put("type","inputStream");
                valueMap.put("data",fileInputStream);
            }
        }
        return valueMap;
    }
}
